<?php

/**
 * API控制器基类
 */
class Gettoken
{
namespace app\common\controller;
/**
     * get_access_token
     * @ApiSummary  (生成订单，返回订单id)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/get_access_token)
     */
    public function get_access_token()
    {
        $config = get_addon_config('third');    
        $config = $config['douyin'];

        $now_time = time();

        $token_data = Db::name('token')->order('id desc')->find();
       
        if($now_time-$token_data['expires_in']>7200||empty($token_data)){
            $config = get_addon_config('third');    
            $config = $config['douyin'];
            $params = [
                'appid'      => $config['appid'],
                'secret'     => $config['secret'],
                'grant_type' => 'client_credential',
            ];

            $http_result = Http::sendRequest("https://developer.toutiao.com/api/apps/token", $params, 'GET');
            if ($http_result['ret']) {
                $json = (array)json_decode($http_result['msg'], true);
                if (isset($json['access_token'])) {
                    $result = [
                        'access_token'  => $json['access_token'],
                        'expires_in'    => $now_time+7200,
                    ];
                    Db::name('token')->insert($result);
                    return $json['access_token'];
                }
            }
        }else{
            return $token_data['access_token'];
        }
        
    }

    
}